// pages/myOrderDetail/myOrderDetail.js订单详情
let url_js = require("../../utils/url.js");
var common_js = require("../../utils/common.js");
var const_js = require("../../utils/const.js");
var user_js = require("../../utils/user.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    orderListStatus: null, //订单列表传过来的状态，如果有的话更新上个页面的数据
    userInfo: null,
    item: null,
    topDes: "",
    isPintDetailShow: false,
    contentStatus: -1,
    shareInfo:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //0.禁止转发
    wx.hideShareMenu();
    //1.初始化数据
    this.initData(options);
    //2.请求数据
    this.requestToGetOrderInfo(this.data.orderId);
  },
  //分享信息
  onShareAppMessage(res){
    return {
      title:this.data.shareInfo.shareTitle,
      imageUrl:this.data.shareInfo.shareImag,
      path:`/pages/shareCoupon/shareCoupon?orderId=${this.data.orderId}`
    }
  },
  //判断是否显示分享优惠券弹窗
  getsetting(){
    api.wxRequest2(url_js.getsetting, {
      orderId:this.data.orderId
    }).then(res => {
      if(res.code===200 && res.result && res.result.dealCampaign && res.result.dealCampaign.id){
        this.setData({
          shareInfo:res.result.dealCampaign
        })
        api.wxRequest(url_js.refreshsharecoupon, {
            orderId:this.data.orderId
        }).then(res => {
          if(res.code===200){
            
          }
        }).catch(err => {
          common_js.log(err);
        });
      }
    }).catch(err => {
      common_js.log(err);
    });
  },
  //控制优惠券弹窗是否显示
  hideBox(){
    this.setData({
      shareInfo:this.data.shareInfo?false:true
    })
  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },


  //初始化数据
  initData: function(options) {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    var tmpOrderId = options.orderId ? options.orderId : '';
    var tmpStatus = options.status ? options.status : null;

    this.setData({
      orderId: tmpOrderId,
      orderListStatus: tmpStatus,
      userInfo: tempUserInfo
    });
  },

  //请求数据
  requestToGetOrderInfo: function(orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderInfoUrl, data).then(res => {
      this.handleOrderInfoData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的数据
  handleOrderInfoData: function(res) {
    var des = this.getTopDes(res.result);
    var tmpItem = res.result;
    tmpItem.sxSkuList.forEach((item, index) => {
      item.type = tmpItem.type;
    });
    //计算实际支付金额
    var tmpActualPayment = (tmpItem.totalAmount - tmpItem.couponAmount).toFixed(2);
    tmpItem.actualPayment = tmpActualPayment;
    
    this.setData({
      contentStatus: 1,
      topDes: des,
      item: res.result
    });
    let _time = this.data.item.createTime.replace(/-/g,"/");
    let timeStamp = +new Date(_time);
    //支付完成(待提货状态)判断是否需要分享领券(下单超过1小时不显示)
    this.data.item.status >= 3 && +new Date() - timeStamp < 60*60*1000 && this.getsetting();

    //待提货二次提示
    if (res.result.status == 1) {
      wx.showModal({
        title: "提示",
        content: "该订单商品需要到店自提，请确认自提点：" + res.result.shopVo.shopName,
        showCancel: true,
        cancelText: "取消订单",
        confirmText: "确认订单",
        success: mRes => {
          if (!mRes.confirm) {
            //取消订单，返回页面
            this.requestToOrderCancel(res.result.id);
          }
        }
      });
    }
  },


  //检查是否显示取消按钮
  checkIsCancelBtnShow: function(item) {
    var tmpCancelShow = false;
    if (item.status == 3) {
      var nowDate = new Date().getTime();
      var timeObj = common_js.timestampToTime(nowDate);
      var payTimeDateStr = item.payTime.split(" ")[0];
      var currentDateStr = timeObj.year + '-' + timeObj.month + '-' + timeObj.day;
      if (payTimeDateStr == currentDateStr && timeObj.hour < 23) {
        tmpCancelShow = true;
      }
    } else if (item.status == 1) {
      //代付款
      tmpCancelShow = true;
    }
    return tmpCancelShow;
  },

  //取消订单
  requestToOrderCancel: function(orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderCancelUrl, data).then(res => {
      this.handleOrderCancelData(res, orderId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理取消订单的数据
  handleOrderCancelData: function(res, orderId) {
    common_js.showToast("订单已取消");
    //刷新当前页面
    this.requestToGetOrderInfo(this.data.orderId);
    //通知上个页面也刷新页面
    this.prePageRefreshData();
  },

  //通知上个页面也刷新页面
  prePageRefreshData: function() {
    if (this.data.orderListStatus) {
      var pages = getCurrentPages();
      var prePage = pages[pages.length - 2];
      prePage.onPullDownRefresh();
    }
  },

  //删除订单
  requestToOrderDelete: function(orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderDeleteUrl, data).then(res => {
      this.handleOrderDeleteData(res, orderId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理删除订单的数据
  handleOrderDeleteData: function(res, orderId) {
    //1.提示
    common_js.showToast("订单已删除");
    //2.通知上个页面也刷新页面
    this.prePageRefreshData();
    //3.返回上个页面
    wx.navigateBack({});
  },

  //生成预支付订单
  requestToPayPrepare: function(orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id,
    }
    api.wxRequest(url_js.payPrepareUrl, data).then(res => {
      this.handlePayPrepareData(res, orderId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理生成预支付订单数据
  handlePayPrepareData: function(res, orderId) {
    var payItem = res.result;
    //微信支付
    wx.requestPayment({
      timeStamp: payItem.timeStamp,
      nonceStr: payItem.nonceStr,
      package: payItem.package,
      signType: payItem.signType,
      paySign: payItem.paySign,
      success: res => {
        //刷新页面
        this.handleOrderCancelData();
      },
      fail: res => {
        if (common_js.containsKeyString(res.errMsg, "fail cancel")) {
          //什么也不做
        } else {
          common_js.showToast(res.errMsg);
        }
      }
    })
  },

  //获取顶部描述信息
  getTopDes: function(item) {
    var text = '';
    //拼团中
    if (item.type == 3) {
      if (item.groupBuyStatus == 0) {
        text = "拼团中";
      } else if (item.groupBuyStatus == 1) {
        text = "拼团成功";
      } else if (item.groupBuyStatus == 2) {
        text = "拼团失败";
      }
    }

    return text;
  },

  //联系店长
  contactDz: function(e) {
    if (!this.data.item.shopVo.mobile) {
      common_js.showToast("电话不存在！");
      return
    }
    //打电话
    wx.makePhoneCall({
      phoneNumber: this.data.item.shopVo.mobile
    })
  },

  //复制订单号
  onCopyOrder: function(e) {
    if (!this.data.item || !this.data.item.billNo) {
      common_js.showToast("订单编号不存在");
      return;
    }
    wx.setClipboardData({
      data: this.data.item.billNo
    })
  },

  //删除订单
  onDelete: function(e) {
    this.requestToOrderDelete(this.data.orderId);
  },

  //去支付
  onBuy: function(e) {
    this.requestToPayPrepare(this.data.orderId);
  },

  //取消订单
  onCancel: function(e) {
    common_js.showModal("是否确认取消订单？", null, true, "放弃", "取消订单", () => {
      this.requestToOrderCancel(this.data.orderId);
    });
  },

  //售后详情
  onAfterSale: function(e) {
    wx.navigateTo({
      url: '../myOrderAfterSaleDetail/myOrderAfterSaleDetail?orderId=' + this.data.orderId
    })
  },

  //拼团详情
  onPintDetail: function(e) {
    //跳转到团详情
    wx.navigateTo({
      url: '../myPintuaDetail/myPintuaDetail?groupId=' + this.data.item.groupId
    });
  },
})